import React, { Component } from 'react'
import PropTypes from 'prop-types'
import moment from 'moment'
import _ from 'loadsh'
import { Split, TitleLine, TextLine, TextCell } from '@components/ApprovePre/Approve'
import PayTable from './PayTable'
import MoneyTable from './MoneyTable'

export default class Main extends Component {
  state = {
    keyTitleMap: {},
    isLast: false
  }

  // 格式化日期
  formatDate (date) {
    if (date) {
      return moment(date * 1000).format('YYYY-MM-DD HH:mm')
    }
  }

  formatNum (v) {
    if (typeof v === 'string') {
      return v.replace(/\B(?=(\d{3})+(?!\d))/g, ',')
    }
    return 0
  }

  initKeyTitleMap () {
    const map = {}
    const list = _.get(this.props.action || {}, 'vars', [])
    list.forEach(li => {
      map[li.key] = li.title
    })
    this.setState({
      keyTitleMap: map
    })
  }

  initIsLastOne () {
    const id = this.props.action.id
    const list = (this.props.instance.history || []).filter(li => li.step_key === 'zcybaochou01')
    list.sort((a, b) => b.create_datetime - a.create_datetime)
    this.setState({
      isLast: id === list[0].id
    })
  }

  formatList (o) {
    let r = []
    if (o && typeof o.value === 'string') {
      try {
        r = JSON.parse(o.value)
      } catch (e) {
        console.error(e)
      }
    }
    return r
  }

  componentDidUpdate (prev) {
    if (this.props.instance !== prev.instance) {
      this.initKeyTitleMap()
      this.initIsLastOne()
    }
  }

  componentDidMount () {
    this.initKeyTitleMap()
    this.initIsLastOne()
  }

  render () {
    const { action } = this.props
    const { varsMap } = action
    const { keyTitleMap, isLast } = this.state
    return (
      <div>
        <TitleLine title={this.props.action.step_name} operator={action.operator} time={this.formatDate(action.complete_datetime)} />
        <TextLine>
          <TextCell>{keyTitleMap.zcybaochou_fee_acceptance}：{this.formatNum((varsMap.zcybaochou_fee_acceptance || { value: 0 }).value)} 元</TextCell>
          <Split />
          {/* <TextCell>{keyTitleMap.zcybaochou_hearing_count}：{(varsMap.zcybaochou_hearing_count || { value: 0 }).value} 次</TextCell>
          <Split />
          <TextCell>{keyTitleMap.zcybaochou_closuredoc_count}：{(varsMap.zcybaochou_closuredoc_count || { value: 0 }).value} 字</TextCell> */}
        </TextLine>
        {isLast && this.props.renderDocument()}
        {isLast && <PayTable caseDetail={this.props.caseDetail} />}
        {varsMap.remuneration_list01 && <MoneyTable data={this.formatList(varsMap.remuneration_list01)} />}
      </div>
    )
  }
}

Main.proptypes = {
  userInfo: PropTypes.object,
  instance: PropTypes.object,
  action: PropTypes.object,
  renderDocument: PropTypes.func
}

Main.defaultProps = {
  userInfo: {},
  instance: {},
  action: {},
  renderDocument: () => {}
}
